/*
 * Copyright 2012 Finbudget.com
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package finbudgettable.client.ui.grid.cell.bool;

import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.ui.MenuBar;
import com.google.gwt.user.client.ui.PopupPanel;
import finbudgettable.client.ui.grid.CellGrid;
import finbudgettable.client.ui.grid.cell.ContextMenu;
import finbudgettable.client.ui.grid.cell.ContextMenuPopupPanel;

public class BoolContextMenu implements ContextMenu<Boolean> {

    private final CellGrid grid;
    private final String fieldName;

    private MenuBar menu;
    private PopupPanel popupPanel;

    private final Command filterSelected = new Command() {
        @Override
        public void execute() {
            grid.getFilter().setFilter(fieldName, new TrueBoolFilter(fieldName));
            grid.filter();
            popupPanel.hide();
            grid.setFocus(true);
        }
    };

    private final Command filterNotSelected = new Command() {
        @Override
        public void execute() {
            grid.getFilter().setFilter(fieldName, new FalseBoolFilter(fieldName));
            grid.filter();
            popupPanel.hide();
            grid.setFocus(true);
        }
    };

    public BoolContextMenu(CellGrid grid, String fieldName) {
        this.grid = grid;
        this.fieldName = fieldName;
    }

    private void ensureCreate() {
        if (popupPanel != null) {
            return;
        }
        popupPanel = new ContextMenuPopupPanel(grid);
        menu = new MenuBar(true);
        menu.setAutoOpen(false);
        menu.addStyleName(ContextMenuPopupPanel.RESOURCES.style().bCellContextMenu());
        menu.addItem(BoolFilterPanel.STRINGS.selected(), filterSelected);
        menu.addItem(BoolFilterPanel.STRINGS.notSelected(), filterNotSelected);
        popupPanel.add(menu);
    }

    @Override
    public void show(int x, int y, Element parent, Boolean value) {
        ensureCreate();
        popupPanel.setPopupPosition(x, y);
        popupPanel.show();
        menu.focus();
    }

}
